
#import "RoomGalleryViewController.h"
#import "RoomGalleryRoomViewController.h"
#import "SlidingView.h"
#import "GalleryRoom.h"

#define kInfoContainerCornerRadius 10

@interface RoomGalleryViewController () <UIScrollViewDelegate, UIWebViewDelegate, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *darknessView;
@property (weak, nonatomic) IBOutlet UIScrollView *roomsScrollView;
@property (weak, nonatomic) IBOutlet UIImageView *pageControlImage;
@property (strong, nonatomic) IBOutlet UIView *rightInfoView;
@property (weak, nonatomic) IBOutlet UIWebView *rightInfoWebView;
@property (strong, nonatomic) IBOutlet UIView *topInfoView;
@property (weak, nonatomic) IBOutlet UIWebView *topInfoWebView;

@property (strong, nonatomic) SlidingView *rightSlidingView;
@property (assign, nonatomic) NSInteger currentRoomNumber;

@property (strong, nonatomic) NSArray *roomData;
@property (strong, nonatomic) NSMutableArray *roomViewControllers;

@property (strong, nonatomic) UIView *topSlidingView;

@end

@implementation RoomGalleryViewController

- (instancetype)initWithRooms:(NSArray *)roomData showRoomNumber:(NSInteger)roomNumber
{
    self = [super init];
    if (self) {
        _roomData = roomData;
        _currentRoomNumber = roomNumber;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.topInfoWebView.delegate = self;
    self.topInfoWebView.scrollView.delegate = self;
    self.rightInfoWebView.scrollView.delegate = self;

    self.rightSlidingView = [[SlidingView alloc] initWithLength:440];
    [self.rightSlidingView attachToView:self.view];

    [self.rightSlidingView setControllerSubview:self.rightInfoView];    
    
    [self.view bringSubviewToFront:self.darknessView];
    
    self.topInfoView.layer.cornerRadius = kInfoContainerCornerRadius;
    self.topInfoView.clipsToBounds = YES;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = YES;
    if (!self.roomViewControllers) {
        [self setupRoomViews];
        [self setupRightInfoView];
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [UIApplication sharedApplication].statusBarHidden = NO;

    // Hide sliding view to look nice when going back from landscape w button left
    self.rightSlidingView.dragButton.hidden = YES;
    self.rightSlidingView.hidden = YES;
}

- (void)setupRoomViews {
    [self.view layoutIfNeeded];
    self.roomViewControllers = [NSMutableArray array];
    CGRect frame = self.roomsScrollView.bounds;
    for (NSInteger i = 0; i < self.roomData.count; i++) {
        RoomGalleryRoomViewController *roomViewController = [[RoomGalleryRoomViewController alloc] initWithGalleryRoom:self.roomData[i] roomGalleryViewController:self];
        roomViewController.view.frame = frame;
        [self.roomsScrollView addSubview:roomViewController.view];
        [self addChildViewController:roomViewController];
        [self.roomViewControllers addObject:roomViewController];
        frame.origin.x += frame.size.width;
    }
    frame.size.width *= self.roomData.count;
    self.roomsScrollView.contentSize = frame.size;
    
    // Setup selected room
    [self.roomViewControllers[self.currentRoomNumber] roomViewWillAppear];
    self.roomsScrollView.contentOffset = CGPointMake(self.currentRoomNumber * self.roomsScrollView.bounds.size.width, 0);
    [self pageControlSetPageNumber:self.currentRoomNumber];
    [self.roomViewControllers[self.currentRoomNumber] roomViewSelected];
}

- (void)setupRightInfoView {
    // Create the path (with only the top-left corner rounded)
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.rightSlidingView.bounds
                                                   byRoundingCorners:UIRectCornerBottomLeft
                                                         cornerRadii:CGSizeMake(10.0, 10.0)];
    
    // Create the shape layer and set its path
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.rightSlidingView.bounds;
    maskLayer.path = maskPath.CGPath;
    
    // Set the newly created shape layer as the mask for the image view's layer
    self.rightSlidingView.layer.mask = maskLayer;
}

#pragma mark - Actions
- (IBAction)backButtonPressed {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)darknessViewPressed:(UITapGestureRecognizer *)sender {
    [self hideTopInfoView];
}

- (IBAction)topInfoCloseButtonPressed {
    [self hideTopInfoView];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    if (scrollView == self.roomsScrollView) {
        [self.rightSlidingView hideSliderTab];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == self.roomsScrollView) {
        NSInteger selectedRoomNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width);
        if (selectedRoomNumber != self.currentRoomNumber) {
            [self.roomViewControllers enumerateObjectsUsingBlock:^(RoomGalleryRoomViewController *roomVC, NSUInteger idx, BOOL *stop) {
                if (idx == selectedRoomNumber) {
                    [roomVC roomViewSelected];
                } else {
                    [roomVC roomViewDeselected];
                }
            }];
            self.currentRoomNumber = selectedRoomNumber;
        }
        [self pageControlSetPageNumber:selectedRoomNumber];
        [self.rightSlidingView showSliderTab];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.roomsScrollView) {
        [self roomsScrollViewDidScroll:scrollView];
    } else {
        [self webScrollViewDidScroll:scrollView];
    }
}

-(void)roomsScrollViewDidScroll:(UIScrollView *)scrollView {
    static NSInteger lastWillAppearViewNotified = -1;
    CGFloat scrollFactor = scrollView.contentOffset.x / scrollView.frame.size.width;
    
    if (scrollFactor == (CGFloat)self.currentRoomNumber || scrollFactor == -1) {
        lastWillAppearViewNotified = self.currentRoomNumber;
    } else if (scrollFactor < lastWillAppearViewNotified) {
        NSInteger viewIndex = floor(scrollFactor);
        if (viewIndex != self.currentRoomNumber && viewIndex >= 0) {
            NSLog(@"roomViewWillAppear %ld", (long)viewIndex);
            [self.roomViewControllers[viewIndex] roomViewWillAppear];
            lastWillAppearViewNotified = viewIndex;
        }
    } else {
        NSInteger viewIndex = ceil(scrollFactor);
        if (viewIndex != self.currentRoomNumber && viewIndex < self.roomViewControllers.count) {
            NSLog(@"roomViewWillAppear %ld", (long)viewIndex);
            [self.roomViewControllers[viewIndex] roomViewWillAppear];
            lastWillAppearViewNotified = viewIndex;
        }
    }

    NSInteger pageNumber = round(scrollFactor);
    [self pageControlSetPageNumber:pageNumber];
}

-(void)webScrollViewDidScroll:(UIScrollView *)scrollView {
    scrollView.contentOffset = CGPointMake(0, scrollView.contentOffset.y);
}

#pragma mark - Page Control
-(void)pageControlSetPageNumber:(NSInteger)page {
    static NSInteger currentPage = -1;
    if (page != currentPage) {
        self.pageControlImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"cirklar-%ld", (long)(page + 1)]];
        currentPage = page;
    }
}

#pragma mark - Top Sliding View
- (void)setupTopInfoView {
    CGFloat const kWidth = 400;
    CGRect frame = CGRectMake(round((self.view.bounds.size.width - kWidth) / 2), -150, kWidth, 150);
    self.topSlidingView = [[UIView alloc] initWithFrame:frame];
    self.topSlidingView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.topSlidingView];
    
    [self.topSlidingView addSubview:self.topInfoView];
    NSDictionary *views = @{@"topInfoView": self.topInfoView};
    self.topInfoView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.topSlidingView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[topInfoView]|" options:0 metrics:nil views:views]];
    NSDictionary *metrics = @{@"topMargin": @(-kInfoContainerCornerRadius)};
    [self.topSlidingView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-topMargin-[topInfoView]|" options:0 metrics:metrics views:views]];
}

- (void)showDocumentInTopInfoView:(NSString *)documentName {
    if (!self.topSlidingView) {
        [self setupTopInfoView];
    }

    [self loadDocument:documentName inWebView:self.topInfoWebView];

    // Animation will start when document is loaded. Go to webViewDidFinishLoad: below
}

- (void)hideTopInfoView {
    CGRect newFrame = self.topSlidingView.frame;
    newFrame.origin.y = -newFrame.size.height;
    [UIView animateWithDuration:.3 animations:^{
        self.topSlidingView.frame = newFrame;
        self.darknessView.alpha = 0;
    }];
}

- (void)loadDocumentInRightInfoView:(NSString *)documentName {
    [self loadDocument:documentName inWebView:self.rightInfoWebView];
}

- (void)loadDocument:(NSString *)documentName inWebView:(UIWebView *)webView {
    NSLog(@"loadDocument: %@", documentName);
    NSString *locale = @"sv";
    NSString *file = [locale stringByAppendingFormat:@"_%@", documentName];
    NSString *html = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
                                                         pathForResource:file
                                                         ofType:@"html"]
                                               encoding:NSUTF8StringEncoding error:nil];
    html = [html stringByReplacingOccurrencesOfString:@"../" withString:@""];
    // VoiceOver adaptaion is not needed since this view is not used if VoiceOver is enabled
    webView.dataDetectorTypes = UIDataDetectorTypeNone;
    [webView loadHTMLString:html baseURL:[NSBundle mainBundle].bundleURL];
}

#pragma mark - UIWebViewDelegate (topInfoWebView)
-(void)webViewDidFinishLoad:(UIWebView *)webView {
    CGFloat const kPadding = 8, kMaxHeight = self.view.frame.size.height - 40;

    CGRect frame = self.topSlidingView.frame;
    frame.size.height = kPadding + 5;
    self.topSlidingView.frame = frame;
    [self.topSlidingView layoutIfNeeded];
    
    CGSize neededSize = [webView sizeThatFits:CGSizeZero];
    CGFloat neededHeight = neededSize.height + kPadding;
    if (neededHeight > kMaxHeight) {
        neededHeight = kMaxHeight;
        [webView.scrollView flashScrollIndicators];
    }
    NSLog(@"%f", neededHeight);
    
    frame.size.height = neededHeight;
    frame.origin.y = -frame.size.height;
    self.topSlidingView.frame = frame;
    
    [self.topSlidingView layoutIfNeeded];
    [webView.scrollView setContentSize: CGSizeMake(webView.frame.size.width, webView.scrollView.contentSize.height)];
    webView.scrollView.showsHorizontalScrollIndicator = NO;

    frame.origin.y = 0;
    [UIView animateWithDuration:.3 animations:^{
        self.topSlidingView.frame = frame;
        self.darknessView.alpha = 0.2;
    }];
}


@end
